package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.*;

import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("套餐信息：" + setmealDto);

        setmealService.saveWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={},pageSize={},name={}",page,pageSize,name);
        //构造分页构造器
        Page<Setmeal> pageInfo = new Page(page,pageSize);
        Page<SetmealDto> setmealDtoPage= new Page<>();
        //构造条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper();
        //添加过滤条件
        queryWrapper.like(name!=null,Setmeal::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime).orderByAsc(Setmeal::getCreateTime);
        //执行查询
        setmealService.page(pageInfo, queryWrapper);

        //对象拷贝,records是集合List,存放基本信息，拷贝除records以外的所有信息如：current,pages,size,total
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        List<Setmeal> records = pageInfo.getRecords();

        List<SetmealDto> list=records.stream().map((item)->{
            SetmealDto setmealDto=new SetmealDto();
            //拷贝records所有信息（基本信息）如id,name,price,image,description,status,sort,createTime,updateTime,createUser,updateUser,
            BeanUtils.copyProperties(item,setmealDto);

            Long categoryId = item.getCategoryId();//获取分类Id
            //根据Id查询分类对象
            Category category=categoryService.getById(categoryId);
            //获取分类名称,if语句,避免空指针异常
            if (category!=null){
                String categoryName=category.getName();
                setmealDto.setCategoryName(categoryName);
            }

            return setmealDto;
        }).collect(Collectors.toList());//转换流，将list转换为流，返回给setmealDtoPage，collect(Collectors.toList())将信息转换为集合

        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }


    /**
     * 删除套餐/批量删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("删除套餐，id为：{}",ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐信息删除成功");
    }

    /**
     * 根据id和状态修改套餐状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status,@RequestParam List<Long> ids){
        log.info("status={},ids={}",status,ids);
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        List<Setmeal> list = setmealService.list(queryWrapper);
        for (Setmeal setmeal : list) {
            setmeal.setStatus(status);
            log.info("setmeal={}",setmeal);
            setmealService.updateById(setmeal);
        }

        return R.success("修改成功");
    }

    /**
     * 根据id查询套餐信息和对应的菜品
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> update(@PathVariable Long id) {
        log.info("id: " + id);
        SetmealDto setmealDto = setmealService.getByIdWithDish(id);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐信息
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> save1(@RequestBody SetmealDto setmealDto){
        log.info("setmealDto:{}",setmealDto);
        //调用保存套餐信息
        setmealService.updateWithDish(setmealDto);
        return  R.success("修改套餐成功");
    }

    /**
     * 根据ID查询套餐信息
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    public R<List<SetmealDto>> list(Setmeal setmeal){

        //构造查询条件
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        //添加分类Id条件
        queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        //添加start状态条件
        queryWrapper.eq(Setmeal::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Setmeal::getUpdateTime);

        List<Setmeal> list=setmealService.list(queryWrapper);

        List<SetmealDto> setmealDtoList=list.stream().map((item)->{
            SetmealDto setmealDto=new SetmealDto();
            //拷贝records等所有信息
            BeanUtils.copyProperties(item,setmealDto);

            Long categoryId = item.getCategoryId();//获取分类Id
            //根据Id查询分类对象
            Category category=categoryService.getById(categoryId);
            //获取分类名称,if语句,避免空指针异常
            if (category!=null){
                String categoryName=category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            //当前套餐的id
            Long setmealId=item.getId();
            LambdaQueryWrapper<SetmealDish> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(SetmealDish::getSetmealId,setmealId);
            List<SetmealDish> setmealDish = setmealDishService.list(queryWrapper1);
            //将菜品信息存入SetmealDish
            setmealDto.setSetmealDishes(setmealDish);
            return setmealDto;
        }).collect(Collectors.toList());//转换流，将list转换为流，返回给dishDtoList，collect(Collectors.toList())将信息转换为集合


        return R.success(setmealDtoList);
    }
}
